package com.zhang.consumerserver;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @author zhanghaidong
 */
@RestController
@EnableEurekaClient
@SpringBootApplication
public class ConsumerServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(ConsumerServerApplication.class, args);
    }

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;


    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String hello(String name){
        List<ServiceInstance> instances = discoveryClient.getInstances("eureka-client");
        ServiceInstance instanceInfo = instances.get(0);
        String baseUrl = "http://" + instanceInfo.getHost() + ":" + instanceInfo.getPort() + "/hello?name=" + name;
        return restTemplate.getForObject(baseUrl, String.class);
    }
}
